package com.mybatisflex.admin.spring.error;

import com.alibaba.fastjson.support.spring.annotation.FastJsonView;
import com.mybatisflex.admin.util.Result;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GlobalErrorResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        Result error;
        if (ex instanceof MissingServletRequestParameterException) {
            error = Result.error(1, ((MissingServletRequestParameterException) ex).getParameterName() + " 不能为空.");
        } else {
            ex.printStackTrace();
            error = Result.error(1, ex.getMessage());
        }

        return new ModelAndView(new FastJsonView())
                .addAllObjects(error);
    }
}
